var util = require('../../utils/util.js');
var log = require('../../utils/log.js');
// const { isRegExp } = require('util');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 投递
    height: '100%',
    successlabel: '',
    submitText:'',
    isHaveResume:null,
    mode: true,
    animationData: {},
    positionInfoId:'',
    isHave: '',
    // 投递end
    hasMore: true,
    isOpen:false,
    searchValue: '',
    isDefTap: false,
    fId:[],
    dId:[],
    positions:"",
    companys:"",
    hasUserInfo: false,
    positionPage: {
      loading: false,
      pageNum: 0,
      now_page_no: 1,
      data: [],
      noMore: false,
      param: ''
    },
    currentTab: 0,
    loadingText: '加载中...',//
    loadingHidden: true,//默认隐藏更多
    banner: {},
    cityOption: [
      { text: '地区', value: 0 },
    ],
    cityValue:0,
    bannerUrl:'',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.isHaveResume()
    this.isHaveInfo()
    this.getCity()
    this.setParams(options)
    this.getAdcarouse()
    this.resetData(true,  false, 1);
    this.getBanner(options.pictureId)
  },
  // 判断有没有简历
  isHaveResume(){
    let that = this
    util.post(app.api.isExitResume, { unionid: wx.getStorageSync('unionid') }, function (res) {
      that.setData({
        isHave: res.data,
      })
    })
  },
  // 判断有没有资料
  isHaveInfo(){
    let that = this
    if (app.globalData.openid != null) {
      util.post(app.api.getByUnionid, { unionid: app.globalData.unionid }, function (res) {
        if (res != null) {
          that.setData({
            isHaveResume: res,
          })
          wx.setStorageSync('isHaveResume', that.data.isHaveResume)
        }
      })
    }
  },
  setParams(options){
    var that = this;
    if (app.globalData.userInfo != null) {
      that.setData({ hasUserInfo: true });
    }
    log.info("获取到的参数:"+JSON.stringify(options));
    var functionId = options.functionId;
    var domainId = options.domainId;
    var title = options.title;
    var positions = options.positions;
    var companys = options.companys
    var pictureId = options.pictureId
    if(title== undefined || options.title != null){
      wx.setNavigationBarTitle({
        title: title
      });
    }
    if(functionId == undefined){
      functionId = 0;
    }
    if(domainId == undefined){
      domainId = 0;
    }
    if(companys == undefined){
      companys = ""
    }
    if(positions == undefined){
      positions = ""
    }
    if(pictureId == undefined){
      pictureId = ""
    }
    that.setData({
      fId: functionId,
      dId: domainId,
      positions:positions,
      companys:companys,
      pictureId:pictureId,
    })
  },
  getBanner(pictureId){
    let that = this
    if(pictureId==undefined){
      pictureId=""
    }
    util.request(app.api.getBannerPicture, {pictureId}, 'get').then((res)=>{
      console.log(res.data.url)
      that.setData({
        bannerUrl:res.data.url
      })
    })
  },
  getAdcarouse(){
    let that = this
    util.post(app.api.getAdcarouse, { type: 1 }, function (res) {
      console.log(res.data[0])
      //获取position轮播图
      that.setData({
        banner: res.data[0].image_url
      });
    });
  },
  getJobData(){
    this.resetData(true);
  },
  getCity() {
    var that = this;
    var cityList = that.data.cityOption;
    util.post(app.api.getCities, {}, function (res) {
      let result = res.data;
      const cities = cityList.concat(result);
      that.setData({
        cityOption: cities
      })
    })
  },
  // 选择城市并搜索
  toggleCityValue: function({ detail }){
    this.setData({
      cityValue: detail
    })
    this.resetData(true,  false, 1);
  },
  searchSubmit: function (e) {
    var that = this;
    console.log(e.detail);
    var par = e.detail.value;
    that.setData({
      matchPage: {
        loading: false,
        pageNum: 0,
        now_page_no: 1,
        data: [],
        noMore: false,
        param: par
      },
      searchValue: par
    });
    this.resetData(true,  false, 1);
  },
  //职位详情
  positionDetailTap: function (event) {
    var id = event.currentTarget.dataset.id; // 当前id
    // 切换页面
    wx.navigateTo({
      url: '../position-detail/position-detail?pid=' + id
    });
  },
 
  resetDataForPosition: function (url, now_page_no, isappend) {
    var that = this;
    var currObj = that.data.positionPage;
    util.post(url, {
      positionName:that.data.searchValue,
      city:that.data.cityValue,
      pictureId:that.data.pictureId,
      dId: that.data.dId,
      fId: that.data.fId,
      positions:that.data.positions,
      companys:that.data.companys,
      // companys:'1038,895,967',
      page: now_page_no, 
      pageSize: 10 }, function (res) {
      if (res.data == null) {
        wx.showToast({
          title: '正在加载中......',
          icon: 'loading',
          duration: 1200
        })
        that.setData({
          isDefTap: true
        })
        return;
      }
      if (isappend) {
        if(res.data.length<1){
          that.setData({
            hasMore: false,
          })
          return
        }
        //上拉加载更多
        that.setData({ 'positionPage.loading': false });
        var data = [];
        for (var item in currObj.data) {
          data.push(currObj.data[item]);
        }
        for (var item in res.data) {
          data.push(res.data[item]);
        }
      } else {
        that.setData({
           'positionPage.noMore': false,
            loadingHidden: true
        });
        //下拉刷新 此处停止刷新效果  重置now_page_no为1
        wx.stopPullDownRefresh();
        var data = res.data;
        //wx.showToast({ title: '刷新了' });
      }
      data.forEach(function(item, index){
        item.createDate = util.date_format_time(item.createDate);
      })
      that.setData({ 'positionPage.pageNum': res.pageNum });
      that.setData({ 'positionPage.data': data, isDefTap: true});
    });
    that.setData({
      'positionPage.now_page_no' : now_page_no +1
    })
    var currObj = this.data.positionPage;
    if (currObj.now_page_no >= currObj.pageNum){
      that.setData({
        hasMore: false,
      })
    }else{
      that.setData({
        hasMore: true
      })
    }
  },


  resetData: function (isOnLoad, isappend, now_page_no) {
    var isappend
    if(isappend){
      isappend = true
    }else{
      isappend = false
    }
    var now_page_no = now_page_no == undefined ? 1 : now_page_no;
    var url = "";
    if (isOnLoad) {
      this.resetDataForPosition(app.api.getPublicityJobByParam, now_page_no, isappend);
    } else {
        //最新职位
        url = app.api.getPublicityJobByParam;
        this.resetDataForPosition(url, now_page_no, isappend);
    }
  },
  //发送简历
  isSendTap: function (e) {
    console.log(e,e.detail.target.dataset.id)
    this.setData({
      positionInfoId:e.detail.target.dataset.id
    })
    var that = this
    var formId = e.detail.formId
    if (
      app.globalData.openid != null &&
      !(
        that.data.isHaveResume == null ||
        that.data.isHaveResume == 'binded' ||
        that.data.isHaveResume == 'generated'
      )
    ) {
      var that = this
      if (that.data.isHaveResume === null) {
        that.setData({
          submitText: '请先完善您的个人资料',
          isHaveResume: false,
        })
      } else if(that.data.isHave <= 0){
        wx.showModal({
          title: '请先上传简历',
          content: '点击确认进行简历上传',
          cancelText: '取消',
          cancelColor: '#999',
          confirmText: '确认',
          confirmColor: '#4990E2',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/resume/resume',
              })
              return
            } else if (res.cancel) {
              return
            }
          },
        })
      } else {
        wx.showModal({
          title: '发送确认',
          content: '简历将发送至HR',
          cancelText: '取消',
          cancelColor: '#999',
          confirmText: '确认',
          confirmColor: '#4990E2',
          success: function (res) {
            if (res.confirm) {
              that.setData({
                submitText: '发送资料',
                isHaveResume: true,
              })
              app.loading()
              that.sendResumeFun(formId)
            } else if (res.cancel) {
            }
          },
        })
      }
    } else {
      if (
        that.data.isHaveResume == null ||
        that.data.isHaveResume == 'binded' ||
        that.data.isHaveResume == 'generated'
      ) {
        wx.showModal({
          title: '完善资料',
          content: '请完善您的资料',
          success: function (res) {
            if (res.confirm) {
              wx.reLaunch({
                url: '/pages/information/index',
                // url: '/pages/web-view/web-view',
                // url: '/pages/edit-resume-base/edit-resume-base?type=0',
              })
            } else if (res.cancel) {
            }
          },
        })
      } else {
        wx.showModal({
          title: '请先登录',
          content: '请微信授权登录,并完善您的资料',
          cancelText: '取消',
          cancelColor: '#999',
          confirmText: '确认',
          confirmColor: '#4990E2',
          success: function (res) {
            if (res.confirm) {
              app.loading()
              //that.sendResumeFun();
              wx.reLaunch({
                url: '/pages/user/index',
              })
            } else if (res.cancel) {
            }
          },
        })
      }
    }
  },
  //投递接口
  sendResumeFun: function (formId) {
    var that = this
    util.post(
      app.api.deliveryResume,
      {
        jobid: that.data.positionInfoId,
        unionid: app.globalData.unionid,
        openid: app.globalData.openid,
        formid: formId,
      },
      function (data) {
        if (data.code == '200') {
          app.alert('投递成功')
          that.setData({
            height: '',
            successlabel: '投递成功，请耐心等待HR的反馈！',
          })
          var animation = wx.createAnimation({
            duration: 1000,
            timingFunction: 'ease',
          })

          that.setData({
            mode: false,
            animationData: animation.export(),
            //similarPosi: data.ret,
            submitText: '已申请',
            'yingpinBtn.disabled': true,
          })
          //缓存申请过的职位id
          try {
            var sendPosiArray = wx.getStorageSync('sendPosiArray')
            if (sendPosiArray) {
              // Do something with return value
              sendPosiArray.push(that.data.positionInfoId)
              wx.setStorageSync('sendPosiArray', sendPosiArray)
            } else {
              var sendPosiArray = []
              sendPosiArray.push(that.data.positionInfoId)
              wx.setStorageSync('sendPosiArray', sendPosiArray)
            }
          } catch (e) {
            // Do something when catch error
          }
        } else {
          app.alert(data.msg)
        }
        app.hideloading()
      }
    )
  },
  // 投递
  formSubmit: function (e) {
    var formId = e.detail.formId
    this.collectFormIds(formId) //保存推送码
    //上传保存推送码
    this.saveFormIds()
  },
  collectFormIds: function (formId) {
    var formIds = app.globalData.globalFormIds
    if (!formIds) {
      formIds = []
    }
    var data = { formId: formId, expire: parseInt(new Date().getTime() / 1000) + 604800 }
    formIds.push(data)
    app.globalData.globalFormIds = formIds //保存推送码并赋值给变量
    wx.setStorageSync('globalFormIds', formIds)
  },
  //保存推送码
  saveFormIds: function () {
    var formIds = app.globalData.globalFormIds //获取globalFormIds
    if (formIds != null) {
      formIds = JSON.stringify(formIds)
      app.globalData.globalFormIds = ''
    }
    util.post(
      app.api.saveFormIds,
      { unionid: app.globalData.unionid, openid: app.globalData.openid, formids: formIds, type: 2 },
      function (res) {}
    )
  },
  onOpen(){
    this.setData({
      isOpen:true
    })
  },
  onClose(){
    this.setData({
      isOpen:false
    })
  },
  ondisble(){
    this.selectComponent('#mydropdown').close();
    this.setData({
      isOpen:false
    })
  },
  /** 页面上拉触底事件的处理函数*/
  onReachBottom: function () {
    var currObj = this.data.positionPage;
    if (currObj.loading) return;

    if (currObj.now_page_no >= currObj.pageNum) {
        //最新职位
        this.setData({ 'positionPage.noMore': true });
        this.setData({
          hasMore: false
        })
    } else {
      this.resetData(false,  true, currObj.now_page_no);
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
